/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package history;

import avenue.Session;
import avenue.messageBox;
import java.awt.Color;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import model.Card;
import model.DBManager;
import model.Station;
import model.Vehicle;

/**
 *
 * @author me
 */
public class HistoryPaymentForm extends javax.swing.JFrame {

    /**
     * Creates new form HistoryPaymentForm
     */
    public HistoryPaymentForm() {
        em = DBManager.em;
        initComponents();
        
        
        for(int i=0;i<=jComboBox1.getItemCount()-1;i++) //Βρες τον Σταθμό του χρήστη στο combo
        { 
        Station ss=(Station) jComboBox1.getItemAt(i);
            if (ss.getDescription()==Session.loginUser.getStationId().getDescription())
            {
            jComboBox1.setSelectedIndex(i);
            break;
            }
        }
        
        if (Session.loginUser.getRoleId().getId()!=1){
            jComboBox1.setEnabled(false);
        }
        else
        {jComboBox1.setEnabled(true);
        
        }
        
           getContentPane().setBackground(Color.white);
        //Στοιχιση στο κέντρο 24/2/2013
        setLocationRelativeTo(null);
        
        //Αρχικες τιμες στις ημερομηνίες
        Calendar calendar = Calendar.getInstance();
        Date today=calendar.getTime();
         jenddate.setDate(today);//Σημερινη ημερομηνία
        
        
         calendar.set(2000, 0, 1);
        today=calendar.getTime();//Αρχη εργασίων το 2000
        
       
        jstartdate.setDate(today);
        
        
        //Καθαρισμός της λίστας
       paymentList.clear();
                   
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        paymentQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select pa from Payment pa");
        paymentList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(paymentQuery.getResultList());
        query1 = java.beans.Beans.isDesignTime() ? null : em.createQuery("select v from Vehicle v");
        list1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : query1.getResultList();
        query2 = java.beans.Beans.isDesignTime() ? null : em.createQuery("select ca from Card ca");
        list2 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query2.getResultList());
        query3 = java.beans.Beans.isDesignTime() ? null : em.createQuery("select s from Station s");
        list3 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query3.getResultList());
        stationBoxRenderer1 = new avenue.StationBoxRenderer();
        jLabel8 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jbarcode = new javax.swing.JTextField();
        arKikloforias = new javax.swing.JTextField();
        jenddate = new com.toedter.calendar.JDateChooser();
        jstartdate = new com.toedter.calendar.JDateChooser();
        jButton3 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel9 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/imagesCAL4A9SX.jpg"))); // NOI18N
        getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 101, 53));

        jLabel1.setText("Αρ. Κυκλοφορίας: ");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(77, 101, -1, -1));

        jLabel2.setText("Αρ. Κάρτας (barcode): ");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(79, 136, -1, -1));

        jbarcode.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbarcodeActionPerformed(evt);
            }
        });
        getContentPane().add(jbarcode, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 133, 117, -1));
        getContentPane().add(arKikloforias, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 98, 117, -1));
        getContentPane().add(jenddate, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 133, 148, -1));
        getContentPane().add(jstartdate, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 98, 148, -1));

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cog.png"))); // NOI18N
        jButton3.setText("Ευρεση");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 170, 100, -1));

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, paymentList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cardId.barcode}"));
        columnBinding.setColumnName("Barcode");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${oldBalance}"));
        columnBinding.setColumnName("Πίστωση");
        columnBinding.setColumnClass(java.math.BigDecimal.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fortisi}"));
        columnBinding.setColumnName("Φόρτιση");
        columnBinding.setColumnClass(java.math.BigDecimal.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${paymentTimestamp}"));
        columnBinding.setColumnName("Ημερομηνία");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(50);
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(2).setResizable(false);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(3).setResizable(false);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 204, 607, 512));

        jLabel9.setFont(new java.awt.Font("Snap ITC", 1, 24)); // NOI18N
        jLabel9.setForeground(new java.awt.Color(0, 3, 130));
        jLabel9.setText("TelePass 1.0");
        getContentPane().add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(124, 11, -1, 38));

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel7.setText("Ιστορικό Φορτίσεων");
        getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(124, 63, 170, -1));

        jLabel4.setText("Εως :");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 136, -1, -1));

        jLabel5.setText("Από : ");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 101, -1, -1));

        jComboBox1.setRenderer(stationBoxRenderer1);

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list3, jComboBox1, "stare");
        bindingGroup.addBinding(jComboBoxBinding);

        getContentPane().add(jComboBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 170, 148, -1));

        jLabel6.setText("Σταθμός: ");
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));

        jLabel10.setText("Σταθμός: ");
        getContentPane().add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 170, -1, -1));

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbarcodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbarcodeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jbarcodeActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        Vehicle v;
        Boolean found=true;

        if  (arKikloforias.getText().isEmpty()==false) {//Εχει αριθμος κυκλοφοριας
            query1 = em.createQuery("select v from Vehicle v where v.regNumber=:regNumber").setParameter("regNumber", arKikloforias.getText());
            List <Vehicle> list1 = query1.getResultList();

            if (list1.size()==1) {// Υπάρχει το όχημα?

                v = list1.get(0);

                if (jbarcode.getText().isEmpty()==false){ //Εχει γραψει barcode
                    int bar=0;
                    try{
                        bar=Integer.parseInt(jbarcode.getText());}
                    catch(NumberFormatException nfe){
                    }

                    if (v.getCardId().getBarcode()==bar){// το βρήκε

                        paymentQuery = em.createQuery("select c from Payment c where c.cardId=:cardid and c.paymentTimestamp>=:startD and c.paymentTimestamp<=:endD and c.stationId=:station order by c.paymentTimestamp DESC ").setParameter("cardid", v.getCardId()).setParameter("startD",jstartdate.getDate()).setParameter("endD",jenddate.getDate()).setParameter("station",jComboBox1.getSelectedItem());

                    }
                    else{
                        messageBox.infoBox("Δεν υπάρχει αντιστοιχία μεταξύ κάρτας και οχήματος");
                        found=false;
                    }
                }
                else //Μόνο αριθμό κυκλοφορίας
                { paymentQuery = em.createQuery("select c from Payment c where c.cardId=:cardid and c.paymentTimestamp>=:startD and c.paymentTimestamp<=:endD and c.stationId=:station order by c.paymentTimestamp DESC").setParameter("cardid", v.getCardId()).setParameter("startD",jstartdate.getDate()).setParameter("endD",jenddate.getDate()).setParameter("station",jComboBox1.getSelectedItem());
                }
            }
            else{//Δεν υπάρχει αυτο οχήμα
                messageBox.infoBox("Δεν υπάρχει αυτο οχήματο");
                found=false;
              }
        }
        else//Δεν εχει  γραψει αριθμο κυκλοφοριας
        {
            if (jbarcode.getText().isEmpty()==false){ //Εχει barcode οχι αριθμος κυκλοφοριας
                int bar=Integer.parseInt(jbarcode.getText());
                query2 = em.createQuery("select ca from Card ca where ca.barcode=:cardId").setParameter("cardId", bar);
                list2 = query2.getResultList();
                if (list2.size()>=1) {// Υπάρχει το όχημα?

                    Card ca = (Card)list2.get(0);
                    paymentQuery = em.createQuery("select c from Payment c where c.cardId=:cardid and c.paymentTimestamp>=:startD and c.paymentTimestamp<=:endD and c.stationId=:station order by c.paymentTimestamp DESC").setParameter("cardid", ca.getId()).setParameter("startD",jstartdate.getDate()).setParameter("endD",jenddate.getDate()).setParameter("station",jComboBox1.getSelectedItem());
                }
                else
                { messageBox.infoBox("Δεν υπάρχει αυτή η κάρτα");
                    found=false;
                }
            }
            else{//Δεν εχει barcode οχι αριθμος κυκλοφοριας

                paymentQuery = em.createQuery("select c from Payment c where c.paymentTimestamp>=:startD and c.paymentTimestamp<=:endD and c.stationId=:station order by c.paymentTimestamp DESC").setParameter("startD",jstartdate.getDate()).setParameter("endD",jenddate.getDate()).setParameter("station",jComboBox1.getSelectedItem());

            }

        }

        if (found){
            java.util.Collection data = paymentQuery.getResultList();
            for (Object entity : data) {
                em.refresh(entity);
            }
            paymentList.clear();
            paymentList.addAll(data);
            jTable1.revalidate();
        }
        else
        {paymentList.clear();
         jTable1.revalidate();}

    }//GEN-LAST:event_jButton3ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(HistoryPaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(HistoryPaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(HistoryPaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(HistoryPaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new HistoryPaymentForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField arKikloforias;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jbarcode;
    private com.toedter.calendar.JDateChooser jenddate;
    private com.toedter.calendar.JDateChooser jstartdate;
    private java.util.List list1;
    private java.util.List list2;
    private java.util.List list3;
    private java.util.List<model.Payment> paymentList;
    private javax.persistence.Query paymentQuery;
    private javax.persistence.Query query1;
    private javax.persistence.Query query2;
    private javax.persistence.Query query3;
    private avenue.StationBoxRenderer stationBoxRenderer1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
EntityManager em;
}
